package com.tms.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.Date;

/*-----------------------------------
 *   @Time: 2022/9/5 17:00
 *   @Description: JWT 工具类
-----------------------------------*/
@Slf4j
public class JwtUtil {
    // Token 有效期 (默认为 24小时)
    public static final long EXPIRE = 1000 * 60 * 60 * 24;
    // 自定义的密钥
    public static final String APP_SECRET = "ABCD1234UFO567";

    /**
     * 生成 JWT字符串
     * JSON Web Token , JavaScript Object Notation
     * @param id       用户 ID
     * @param username 用户昵称
     * @return
     */
    public static String getJwtToken(Integer id, String username) {
        String JwtToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("tms")
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRE))
                .claim("id", id.toString())
                .claim("username", username)
                .signWith(SignatureAlgorithm.HS256, APP_SECRET)
                .compact();
        return JwtToken;
    }

    /**
     * 判断 Token 是否存在且有效
     *
     * @param jwtToken Token字符串
     * @return
     */
    public static boolean checkToken(String jwtToken) {
        if (StringUtils.isEmpty(jwtToken)) return false;
        try {
            Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(jwtToken);
        } catch (Exception e) {
            log.error("Token解析失败, {}", e.getMessage());
            return false;
        }
        return true;
    }
    
    /**
     * 根据 Token 获取用户 ID
     *
     * @param token Token
     * @return
     */
    public static String getUserIdByJwtToken(String token) {
        if (StringUtils.isEmpty(token)) return "";
        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(APP_SECRET).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String) claims.get("id");
    }
}
